<?php
namespace app\admin\controller;
use think\Db;
use think\Request;
use think\Controller;
class UpFiles extends Common
{
    public function upload(){
        // 获取上传文件表单字段名
        $fileKey = array_keys(request()->file());
        // 获取表单上传文件
        $file = request()->file($fileKey['0']);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            $result['code'] = 1;
            $result['info'] = lang('Upload success');
            $path=str_replace('\\','/',$info->getSaveName());
            $result['url'] = url('/uploads/'. $path,[],false,true);
            return $result;
        }else{
            // 上传失败获取错误信息
            $result['code'] =0;
            $result['info'] = lang('Upload failure');
            $result['url'] = '';
            return $result;
        }
    }
    public function file(){
        $fileKey = array_keys(request()->file());
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($fileKey['0']);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');

        if($info){
            $result['code'] = 0;
            $result['info'] = lang('Upload success');
            $path=str_replace('\\','/',$info->getSaveName());

            $result['url'] = '/uploads/'. $path;
            $result['ext'] = $info->getExtension();
            $result['size'] = byte_format($info->getSize(),2);
            return $result;
        }else{
            // 上传失败获取错误信息
            $result['code'] =1;
            $result['info'] = lang('Upload failure');
            $result['url'] = '';
            return $result;
        }
    }
    public function importFile($model=null){
        $results = $this->file();
        if($results['code'] == 0){//上传成功
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能import导入
            import("Excel.PHPExcel",PLUGIN_PATH);
            import("Excel.PHPExcel.Writer.Excel2007",PLUGIN_PATH);
            import("Excel.PHPExcel.Writer.Excel5",PLUGIN_PATH);
            import("Excel.PHPExcel.IOFactory",PLUGIN_PATH);
            $PHPExcel = new \PHPExcel();
            if($results['ext'] == 'xlsx'){
                $PHPReader = new \PHPExcel_Reader_Excel2007();
            }else{
                $PHPReader = new \PHPExcel_Reader_Excel5();
            }
            //载入文件
            $PHPExcel = $PHPReader->load(ROOT_WWW."/public".$results['url']);
            $currentSheet = $PHPExcel->getSheet(0);
            //获取总列数
            $allColumn = $currentSheet->getHighestColumn();
            $columns = [];
            for ($i = 'A'; $i <= $allColumn; $i++) {
                $value = $currentSheet->getCell($i."1")->getValue();
                if(empty($value)) continue;
                $columns[$i] = $value;
            }
            /*模型*/
            if(!empty($model)){
                $fields = model($model)->getTableFields();
                foreach($fields as $field){
                    $fieldsArr[$field] = lang("field_".$field);
                }
                $results['fields'] = $fieldsArr;
            }
            $results['columns'] = $columns;
        }   
        return $results;
    }
    public function pic(){
        // 获取上传文件表单字段名
        $fileKey = array_keys(request()->file());
        // 获取表单上传文件
        $file = request()->file($fileKey['0']);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            $result['code'] = 1;
            $result['info'] = lang('Upload success');
            $path=str_replace('\\','/',$info->getSaveName());
            $result['url'] = '/uploads/'. $path;
            return json_encode($result,true);
        }else{
            // 上传失败获取错误信息
            $result['code'] =0;
            $result['info'] = lang('Upload failure');
            $result['url'] = '';
            return json_encode($result,true);
        }
    }
    //编辑器图片上传
    public function editUpload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            $result['code'] = 0;
            $result['msg'] = lang('Upload success');
            $path=str_replace('\\','/',$info->getSaveName());
            $result['data']['src'] = request()->domain().__PUBLIC__.'/uploads/'. $path;
            $result['data']['title'] = $path;
            return json_encode($result,true);
        }else{
            // 上传失败获取错误信息
            $result['code'] =1;
            $result['msg'] = lang('Upload failure');
            $result['data'] = '';
            return json_encode($result,true);
        }
    }
    //多图上传
    public function upImages(){
        $fileKey = array_keys(request()->file());
        // 获取表单上传文件
        $file = request()->file($fileKey['0']);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            $result['code'] = 0;
            $result['msg'] = lang('Upload success');
            $path=str_replace('\\','/',$info->getSaveName());
            $result["src"] = '/uploads/'. $path;
            return $result;
        }else{
            // 上传失败获取错误信息
            $result['code'] =1;
            $result['msg'] = lang('Upload failure');
            return $result;
        }
    }
    /*import*/
    public function import($model=null){
        if($this->request->isPost()){
            $data = $this->request->post();
            $ext = fileext(basename($data['importfile']));
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能import导入
            import("Excel.PHPExcel",PLUGIN_PATH);
            import("Excel.PHPExcel.Writer.Excel2007",PLUGIN_PATH);
            import("Excel.PHPExcel.Writer.Excel5",PLUGIN_PATH);
            import("Excel.PHPExcel.IOFactory",PLUGIN_PATH);
            $PHPExcel = new \PHPExcel();
            if($ext == 'xlsx'){
                $PHPReader = new \PHPExcel_Reader_Excel2007();
            }else{
                $PHPReader = new \PHPExcel_Reader_Excel5();
            }
            //载入文件
            $PHPExcel = $PHPReader->load(ROOT_WWW."/public".$data['importfile']);
            $currentSheet = $PHPExcel->getSheet(0);
            //获取总行数
            $allRow = $currentSheet->getHighestRow();
            $bases = [];
            $pk = $data['pk'];
            for ($i = 2; $i <= $allRow; $i++) {
                $base = [];
                $condition = [];
                foreach($data['fields'] as $key=>$value){
                    if(empty($value)) continue; //没有选
                    $val = $currentSheet->getCell($key.$i)->getFormattedValue();
                    $base[$value] = $val;
                    if($pk[$key] == 1){
                        $condition[$value] = $val;
                    }
                }
                if(count($base) > 0){
                    /*有主建*/
                    if(count($condition) > 0){
                        if(model($data['model'])->where($condition)->find()){
                            model($data['model'])->where($condition)->update($base);
                            continue;
                        }
                    }
                    $bases[] = $base;
                }
            }
            if($bases){
                model($data['model'])->insertAll($bases);
            }
            return ['code'=>1,'msg'=>lang('successful.')];
             return ['code'=>0,'msg'=>lang('Failed.')];
        }
        $this->assign('model',$model);
        return $this->fetch('common/import');
    }
}